﻿using BlackList.Utils;
using QWManage.DAL;
using QWManage.Excel;
using QWManage.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BlackList.Forms
{
    public partial class FrmUsersRequired : Form
    {
        private Thread _thread;

        private ListViewColumnSorter lvwColumnSorter;
        private DepartmentDAL _departmentDAL = new DepartmentDAL();
        public FrmUsersRequired()
        {
            InitializeComponent();
        }
        private void setDepartments()
        {
            DepartmentInfo department = _departmentDAL.GetSubDepartments(0)[0];
            btnDepartments.Text = "选择部门";
            btnDepartments.Tag = department;
            foreach (var departmentInfo in _departmentDAL.GetSubDepartments(department.ID))
            {
                ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem();
                toolStripMenuItem.Text = departmentInfo.Name;
                toolStripMenuItem.Tag = departmentInfo;
                toolStripMenuItem.Click += ToolStripMenuItem_Click;
                btnDepartments.DropDownItems.Add(toolStripMenuItem);
                setSubToolStripMenuItem(toolStripMenuItem);
            }
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            lvUsers.Items.Clear();
            DepartmentInfo department = (DepartmentInfo)(sender as ToolStripMenuItem).Tag;
            btnDepartments.Text = department.Name;
            UsersDepartmentsRDAL usersDepartmentsRDAL = new UsersDepartmentsRDAL();
            UserDAL userDAL = new UserDAL();
            List<string> userids = usersDepartmentsRDAL.GetUserIds(department.ID);
            foreach (string userId in userids)
            {
                UserInfo userInfo = userDAL.GetUserInfo(userId);
                ListViewItem lvItem = new ListViewItem();
                lvItem.Tag = userInfo;
                lvItem.Text = userInfo.UserID;
                lvItem.SubItems.Add(userInfo.Name);
                lvItem.SubItems.Add(userInfo.Alias);
                lvItem.SubItems.Add(userInfo.YiYeUserId);
                lvItem.SubItems.Add(
                    userInfo.Required.HasValue && userInfo.Required != 0 ? "已启用" : ""
                    ); ;
                lvUsers.Items.Add(lvItem);
            }
        }

        private void setSubToolStripMenuItem(ToolStripMenuItem toolStripMenuItem)
        {
            DepartmentInfo department = toolStripMenuItem.Tag as DepartmentInfo;
            foreach (var departmentInfo in _departmentDAL.GetSubDepartments(department.ID))
            {
                ToolStripMenuItem subMenuItem = new ToolStripMenuItem();
                subMenuItem.Text = departmentInfo.Name;
                subMenuItem.Tag = departmentInfo;
                subMenuItem.Click += ToolStripMenuItem_Click;
                toolStripMenuItem.DropDownItems.Add(subMenuItem);
                setSubToolStripMenuItem(subMenuItem);
            }
        }

        private void FrmUsersRequired_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            this.FormClosing += (ss, ee) =>
            {
                if (_thread != null && _thread.IsAlive) _thread.Abort();
            };

            lvUsers.Items.Clear();
            lvUsers.View = View.Details;
            lvUsers.MultiSelect = true;
            lvUsers.FullRowSelect = true;
            int width = lvUsers.Width / 5 - 5;
            lvwColumnSorter = new ListViewColumnSorter();
            this.lvUsers.ListViewItemSorter = lvwColumnSorter;
            lvUsers.MouseDoubleClick += LvUsers_MouseDoubleClick;
            lvUsers.ColumnClick += LvUsers_ColumnClick;
            lvUsers.Columns.Add(new ColumnHeader() { Name = "UserID", Text = "UserID", Width = width });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Name", Text = "Name", Width = width });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Alias", Text = "Alias", Width = width });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "YiYeUserId", Text = "YiYeUserId", Width = width });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "启用状态", Text = "启用状态", Width = width });

            setDepartments();
        }

        private void LvUsers_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = lvUsers.GetItemAt(e.X, e.Y);
            if (item == null) return;
            UserInfo userInfo = item.Tag as UserInfo;
            FrmYiYeUserId frm = new FrmYiYeUserId(userInfo);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                item.SubItems[3].Text = userInfo.YiYeUserId;
            }
        }

        private void LvUsers_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.lvUsers.Sort();
        }

        private void btnEnabled_Click(object sender, EventArgs e)
        {
            if (lvUsers.SelectedItems.Count == 0)
            {
                MessageBox.Show(
                    "请先选择用户！",
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }
            UserDAL userDAL = new UserDAL();
            foreach (ListViewItem lvItem in lvUsers.SelectedItems)
            {
                UserInfo userInfo = lvItem.Tag as UserInfo;
                userInfo.Required = 1;
                userDAL.UpdateRequired(userInfo.UserID, userInfo.Required.Value);
                lvItem.SubItems[4].Text = "已启用";
            }
        }

        private void btnForbidden_Click(object sender, EventArgs e)
        {
            if (lvUsers.SelectedItems.Count == 0)
            {
                MessageBox.Show(
                    "请先选择用户！",
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }
            UserDAL userDAL = new UserDAL();
            foreach (ListViewItem lvItem in lvUsers.SelectedItems)
            {
                UserInfo userInfo = lvItem.Tag as UserInfo;
                userInfo.Required = 0;
                userDAL.UpdateRequired(userInfo.UserID, userInfo.Required.Value);
                lvItem.SubItems[4].Text = "";
            }
        }

        private void btnSelectNone_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvItem in lvUsers.Items)
                lvItem.Selected = false;
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvItem in lvUsers.Items)
                lvItem.Selected = true;
        }
        private void importService(object obj)
        {
            try
            {
                foreach (Control control in toolStrip1.Controls) control.Enabled = false;
                toolStripProgressBar.Enabled = true;
                lvUsers.Enabled = false;

                this.Cursor = Cursors.WaitCursor;
                string fn = (string)obj;
                var table = ExcelHelper.ExcelToDataTable(fn);
                UserDAL userDAL = new UserDAL();
                toolStripProgressBar.Minimum = 0;
                toolStripProgressBar.Maximum = table.Rows.Count;
                toolStripProgressBar.Value = 0;
                foreach (DataRow dr in table.Rows)
                {
                    toolStripProgressBar.Value += 1;
                    string yiyeUserId = getCellValue(dr["名称"]);
                    string userID = getCellValue(dr["对应企业微信成员账号（userid）"]);
                    string name = getCellValue(dr["对应企业微信成员名称"]);
                    //根据UserID来更新yiyeUserId
                    userDAL.UpdateYiYeUserId(userID, yiyeUserId);
                }
                MessageBox.Show("导入完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in toolStrip1.Controls) control.Enabled = true;
                lvUsers.Enabled = true;
                this.Cursor = Cursors.WaitCursor;
            }
        }
        private void btnImportYiYeUserIds_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "表格文件(*.xlsx)|*.xlsx";
            if (dlg.ShowDialog() != DialogResult.OK) return;

            _thread = new Thread(new ParameterizedThreadStart(importService));
            _thread.Start(dlg.FileName);
        }
        private string getCellValue(object obj)
        {
            if (obj == null || obj == DBNull.Value) return "";
            return ((string)obj).Trim();
        }
    }
}
